package com.xh.bussiness.teachbook.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.bussiness.exam.model.UserErrorQuestion;
import com.xh.bussiness.exam.service.IUserErrorQuestionService;
import com.xh.bussiness.permission.model.UserArea;
import com.xh.bussiness.permission.model.UserSchool;
import com.xh.bussiness.permission.service.IUserAreaService;
import com.xh.bussiness.permission.service.IUserSchoolService;
import com.xh.bussiness.system.model.Teacher;
import com.xh.bussiness.system.service.ITeacherService;
import com.xh.bussiness.teachbook.bean.dto.NowTeachingBookStudentResultDto;
import com.xh.bussiness.teachbook.bean.dto.StudentErrorQuestionResultDto;
import com.xh.bussiness.teachbook.bean.dto.TeachingBookDto;
import com.xh.bussiness.teachbook.bean.dto.TeachingBookQuestionStudentResultDto;
import com.xh.bussiness.teachbook.bean.request.*;
import com.xh.bussiness.teachbook.constant.TeachingBookConstant;
import com.xh.bussiness.teachbook.dao.*;
import com.xh.bussiness.teachbook.model.*;
import com.xh.bussiness.teachbook.service.*;
import com.xh.bussiness.thirdapi.LongwenApi;
import com.xh.bussiness.tiku.bean.dto.QuestionDto;
import com.xh.bussiness.tiku.service.IQuestionService;
import com.xh.core.bean.XhPage;
import com.xh.core.exception.XhException;
import com.xh.core.service.impl.BaseServiceImpl;
import com.xh.core.util.CacheUtils;
import com.xh.core.util.DateUtils;
import com.xh.core.util.OfficeUtils;
import com.xh.core.util.UserUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class TeachingBookServiceImpl extends BaseServiceImpl<TeachingBookMapper, TeachingBook> implements ITeachingBookService {

    Logger log = LoggerFactory.getLogger(TeachingBookServiceImpl.class);

    @Autowired
    private TeachingBookModuleDetailMapper teachingBookModuleDetailMapper;
    @Autowired
    private ITeachingBookModuleService teachingBookModuleService;
    @Autowired
    private ITeachingBookModuleDetailService teachingBookModuleDetailService;
    @Autowired
    private TeachingBookPracticeMapper teachingBookPracticeMapper;
    @Autowired
    private TeachingBookPracticeContentMapper teachingBookPracticeContentMapper;
    @Autowired
    private ITeachingBookTemplateService teachingBookTemplateService;
    @Autowired
    private TeachingBookPlanBindMapper teachingBookPlanBindMapper;
    @Autowired
    private ITeachingBookNumberService teachingBookNumberService;
    @Autowired
    private ITeachingBookAuditRecordService teachingBookAuditRecordService;
    @Autowired
    private IQuestionService questionService;
    @Autowired
    private IUserSchoolService userSchoolService;
    @Autowired
    private ITeacherService teacherService;
    @Autowired
    private ITeachingBookStudentQuestionResultService teachingBookStudentQuestionResultService;
    @Autowired
    private IUserErrorQuestionService userErrorQuestionService;
    @Autowired
    private IUserAreaService userAreaService;
    @Autowired
    private ITeachingBookStudentResultService teachingBookStudentResultService;


    @Override
    public TeachingBookDto getTeachingBookById(String id) {
        TeachingBookDto teachingBookDto = this.getById(id, TeachingBookDto.class);
        teachingBookDto.setModules(teachingBookModuleService.queryTeachingBookModuleListByParentId(id));
        if (teachingBookDto != null) {
            QueryWrapper qw = new QueryWrapper();
            qw.eq("teaching_book_id", teachingBookDto.getId());
            TeachingBookPlanBind teachingBookPlanBind = teachingBookPlanBindMapper.selectOne(qw);
            if (teachingBookPlanBind != null) {
                teachingBookDto.setTeachingPlanDetailId(teachingBookPlanBind.getPlanDetailId());
            }
        }
        return teachingBookDto;
    }

    @Override
    public XhPage queryTeachingBookPage(XhPage page, QueryTeachingBookRequest request) {
        if (request.getAreaId() != null) {
            //根据区域获取龙文校区id
            Map<String, Object> schoolMap = LongwenApi.querySchoolByAreaId(request.getAreaId());
            if (!CollectionUtils.isEmpty(schoolMap)) {
                request.setSchoolId(schoolMap.get("SCHOOLID") == null ? null : schoolMap.get("SCHOOLID").toString());
            } else {
                return page;
            }
        } else if (request.getAreaId() == null && request.getSchoolId() == null && StringUtils.isEmpty(request.getRefId())) {
            //查询自己所拥有地区数据权限的数据
            String currentUserId = UserUtils.getCurrentUserId();
            List<UserArea> userAreas = userAreaService.queryByUserId(currentUserId, 4);
            if (CollectionUtils.isEmpty(userAreas)) {
                return page;
            }
            List<String> schoolIds = userAreas.stream().map(item -> item.getAreaId().toString()).collect(Collectors.toList());
            request.setSchoolIds(schoolIds);
        }
        return this.dao.queryPage(page, request);
    }


    @Override
    public String addTeachingBook(TeachingBookRequest bean) {
        bean.setTeachingBookType(TeachingBookConstant.TeachingBooType.USER_DEFINED);
        TeachingBook tb = saveTeachingBook(bean);
        //用于保存箐优网试题
        Map<String, QuestionDto> duplicateQuesIdMapValid = new HashMap<>();
        List<QuestionDto> questionDtos = new ArrayList<>();
        //备课模块详情
        List<TeachingBookModuleRequest> moduleRequestList = bean.getTeachingBookModuleRequestList();
        for (TeachingBookModuleRequest teachingBookModuleRequest : moduleRequestList) {
            TeachingBookTemplate teachingBookTemplate = teachingBookTemplateService.getById(teachingBookModuleRequest.getId());
            TeachingBookModule teachingBookModule = new TeachingBookModule();
            teachingBookModule.setTeachingBookId(tb.getId());
            teachingBookModule.setTeachingBookModuleId(teachingBookTemplate.getId());
            teachingBookModuleService.insert(teachingBookModule);
            //课后练习
            if (teachingBookTemplate.getType().equals(TeachingBookConstant.TeachingBookTemplate.PRACTICE) &&
                    teachingBookModuleRequest.getTeachingBookPracticeRequest() != null) {
                TeachingBookPracticeRequest teachingBookPracticeRequest = teachingBookModuleRequest.getTeachingBookPracticeRequest();
                TeachingBookPractice practice = new TeachingBookPractice();
                practice.setTeachingBookId(tb.getId());
                practice.setTotalScore(teachingBookPracticeRequest.getTotalScore());
                practice.setUseTime(teachingBookPracticeRequest.getUseTime());
                practice.setYear(teachingBookPracticeRequest.getYear());
                practice.setMonth(teachingBookPracticeRequest.getMonth());
                practice.setDay(teachingBookPracticeRequest.getDay());
                teachingBookPracticeMapper.insert(practice);

                List<TeachingBookPracticeContentRequest> practiceContentRequests = teachingBookPracticeRequest.getContentDtos();
                if (!CollectionUtils.isEmpty(practiceContentRequests)) {
                    //备课练习内容
                    int j = 1;
                    for (TeachingBookPracticeContentRequest practiceContentRequest : practiceContentRequests) {
                        TeachingBookPracticeContent practiceContent = new TeachingBookPracticeContent();
                        practiceContent.setPracticeId(practice.getId());
                        practiceContent.setTeachingBookId(tb.getId());
                        practiceContent.setContentType(practiceContentRequest.getContentType());
                        practiceContent.setQuestionId(practiceContentRequest.getQuestionId());
                        practiceContent.setSubject(practiceContentRequest.getSubject());
                        practiceContent.setScore(practiceContentRequest.getScore());
                        practiceContent.setContent(practiceContentRequest.getContent());
                        practiceContent.setOrderNo(j);
                        practiceContent.setBlankLine(practiceContentRequest.getBlankLine());
                        teachingBookPracticeContentMapper.insert(practiceContent);
                        //插入试题id
                        //自编题无须保存处理
                        if (practiceContentRequest.getQuestionSource() != null && practiceContentRequest.getQuestionSource().equals(2)) {
                            continue;
                        }
                        if (!StringUtils.isEmpty(practiceContentRequest.getQuestionId())
                                && !StringUtils.isEmpty(practiceContentRequest.getSubject())) {
                            if (!duplicateQuesIdMapValid.containsKey(practiceContentRequest.getQuestionId())) {
                                QuestionDto question = practiceContentRequest.getQuestion();
                                duplicateQuesIdMapValid.put(practiceContentRequest.getQuestionId(), question);

                                questionDtos.add(question);
                            }
                        }
                        j++;
                    }

                }
                TeachingBookModuleDetail detail = new TeachingBookModuleDetail();
                detail.setTeachingBookId(tb.getId());
                detail.setTeachingBookModuleId(teachingBookModuleRequest.getId());
                //课后练习
                detail.setContentType(TeachingBookConstant.ModuleContentType.PRACTICE);
                detail.setResourceId(practice.getId());

                teachingBookModuleDetailMapper.insert(detail);
                continue;
            }
            List<TeachingBookModuleDetailRequest> moduleDetailRequests = teachingBookModuleRequest.getTeachingBookModuleDetailRequest();
            if (CollectionUtils.isEmpty(moduleDetailRequests)) {
                continue;
            }
            int i = 1;
            for (TeachingBookModuleDetailRequest moduleDetailRequest : moduleDetailRequests) {
                TeachingBookModuleDetail detail = new TeachingBookModuleDetail();
                detail.setTeachingBookId(tb.getId());
                detail.setTeachingBookModuleId(teachingBookModuleRequest.getId());
                detail.setContentType(moduleDetailRequest.getContentType());

                detail.setContent(moduleDetailRequest.getContent());
                detail.setMindMapImgPath(moduleDetailRequest.getMindMapImgPath());
                detail.setResourceId(moduleDetailRequest.getResourceId());
                detail.setSubject(moduleDetailRequest.getSubject());
                detail.setOrderNo(i);
                detail.setBlankLine(moduleDetailRequest.getBlankLine());

                teachingBookModuleDetailMapper.insert(detail);
                //如果为变试题、普通试题、相似题 检查是否保存到本地题库
                if ((moduleDetailRequest.getContentType().equals(2) ||
                        moduleDetailRequest.getContentType().equals(3) ||
                        moduleDetailRequest.getContentType().equals(9)) &&
                        !StringUtils.isEmpty(moduleDetailRequest.getSubject()) && !duplicateQuesIdMapValid.containsKey(moduleDetailRequest.getResourceId())) {
                    QuestionDto question = moduleDetailRequest.getQuestion();
                    duplicateQuesIdMapValid.put(moduleDetailRequest.getResourceId(), question);
                    questionDtos.add(question);
                }
                i++;
            }
        }
        //同步箐优网试题到本地
        try {
            if (!CollectionUtils.isEmpty(questionDtos)) {
                for (QuestionDto questionDto : questionDtos) {
                    questionDto.setSourceFrom(2);
                    questionService.addQuestion(questionDto);
                }
            }
        } catch (Exception e) {
            log.error("保存备课同步试题异常：" + e.getMessage());
        }
        return tb.getId();
    }


    @Override
    public String addTeachingBookByFile(TeachingBookRequest bean, HttpServletRequest request) {
        bean.setTeachingBookType(TeachingBookConstant.TeachingBooType.FILE);
        TeachingBook teachingBook = saveTeachingBook(bean);
        String uploadPath = request.getSession().getServletContext().getRealPath("/");
        boolean flag = OfficeUtils.word2pdf(uploadPath + bean.getUploadFilePath(), uploadPath + bean.getUploadFilePath() + ".pdf", null);
        if (flag) {
            teachingBook.setFileConvertPath(bean.getUploadFilePath() + ".pdf");
            teachingBook.setAuditStatus(TeachingBookConstant.TeachingBookAuditStatus.SAVED);
            this.update(teachingBook);
        }else{
            throw new XhException("文件转换失败");
    }
        return teachingBook.getId();
    }

    private TeachingBook saveTeachingBook(TeachingBookRequest bean) {
        if (!StringUtils.isEmpty(bean.getLwPaikeId()) || !StringUtils.isEmpty(bean.getId())) {
            TeachingBook teachingBook = null;
            if (!StringUtils.isEmpty(bean.getLwPaikeId())) {
                teachingBook = this.queryByPaikeId(bean.getLwPaikeId());
            } else if (!StringUtils.isEmpty(bean.getId())) {
                teachingBook = this.getById(bean.getId());
            }
            if (teachingBook != null) {
                //删除讲义相关内容
                deleteTeachingBookByDetailById(teachingBook.getId());
                this.dao.deleteById(teachingBook.getId());
            }
        }
        TeachingBook tb = new TeachingBook();
        //添加教案
        BeanUtils.copyProperties(bean, tb);
        this.insert(tb);

        if (!StringUtils.isEmpty(bean.getTeachingPlanDetailId())) {
            teachingBookPlanBindMapper.deleteByPlanDetailId(bean.getTeachingPlanDetailId());
            //讲义和计划绑定关系
            TeachingBookPlanBind teachingBookPlanBind = new TeachingBookPlanBind();
            teachingBookPlanBind.setPlanDetailId(bean.getTeachingPlanDetailId());
            teachingBookPlanBind.setTeachingBookId(tb.getId());
            teachingBookPlanBind.setLwPaikeId(bean.getLwPaikeId());
            teachingBookPlanBind.setClassTimeStr(bean.getClassTimeStr());
            teachingBookPlanBindMapper.insert(teachingBookPlanBind);
        }
        return tb;
    }

    @Override
    public String bindPaike2TeachingBook(BindPaike2TeachingBookRequest request) {
        String teachingBookId = request.getTeachingBookId();
        if (StringUtils.isEmpty(teachingBookId) || StringUtils.isEmpty(request.getLwPaikeId())) {
            return "参数错误";
        }
        TeachingBook teachingBook = this.getById(teachingBookId);
        if (teachingBook == null) {
            return "备课数据不存在";
        }
        BeanUtils.copyProperties(request, teachingBook);
        this.update(teachingBook);
        return null;
    }


    public void deleteTeachingBookByDetailById(String teachingBookId) {
        // teachingBookNumberService.deleteByTeachingBookId(teachingBookId);
        teachingBookPlanBindMapper.deleteByTeachingBookId(teachingBookId);
        teachingBookModuleService.deleteByTeachingBookId(teachingBookId);
        teachingBookModuleDetailMapper.deleteByTeachingBookId(teachingBookId);
        teachingBookPracticeMapper.deleteByTeachingBookId(teachingBookId);
        teachingBookPracticeContentMapper.deleteByTeachingBookId(teachingBookId);
    }

    @Override
    public String modifyTeachingBook(TeachingBookRequest bean) {
        TeachingBook tb = this.getById(bean.getId());
        if (tb == null) {
            return "该教案不存在";
        }
        return null;
    }


    @Override
    public String deleteTeachingBook(String id) {
        TeachingBook tb = this.getById(id);

        return null;
    }


    @Override
    public List<TeachingBook> queryToAudit(Integer status) {
        QueryWrapper qw = new QueryWrapper<TeachingBook>();
        qw.eq("audit_status", status);
        return this.dao.selectList(qw);
    }


    @Override
    public List<TeachingBook> queryPublisded(Integer status) {
        QueryWrapper qw = new QueryWrapper<TeachingBook>();
        qw.eq("publis_status", status);
        return this.dao.selectList(qw);
    }


    @Override
    public TeachingBook auditTeachingBook(String id, Integer status, String remark, JSONObject currentUser) {
        TeachingBook teachingBook = this.getById(id);
        if (teachingBook == null) {
            throw new XhException("该教案不存在");
        }
        //审核状态（0草稿，1提交，2组长审核通过，3主任审核通过，4审核驳回）
        if (status.equals(1)) {
            //更新提交时间
            if (status.equals(1)) {
                teachingBook.setSubmitTime(new Date());
            }
            TeachingBookNumber number = teachingBookNumberService.queryTeachingBookNumberByTeachingBookId(teachingBook.getId());
            if (number == null) {
                //备课次数
                teachingBookNumberService.saveTeachingBookNumber(teachingBook.getId(), teachingBook.getRefId(), teachingBook.getRefType().toString(), teachingBook.getContractId() == null ? null : teachingBook.getContractId().toString());
            }
        }
        teachingBook.setAuditStatus(status);

        //添加审核记录
        TeachingBookAuditRecord auditRecord = new TeachingBookAuditRecord();
        auditRecord.setTeachingBookId(id);
        auditRecord.setAuditStatus(status);
        auditRecord.setRemark(remark);
        if (currentUser != null) {
            auditRecord.setAuditorId(currentUser.getString("id"));
            auditRecord.setAuditorName(currentUser.getString("username"));

            String auditorId = teachingBook.getAuditorId();
            String auditorName = teachingBook.getAuditorName();
            if (status.equals(2) || status.equals(3)) {
                if (StringUtils.isEmpty(auditorId) && StringUtils.isEmpty(auditorName)) {
                    teachingBook.setAuditorId(currentUser.getString("id"));
                    teachingBook.setAuditorName(currentUser.getString("username"));
                } else {
                    if (auditorId.indexOf(auditorId) < 0) {
                        teachingBook.setAuditorId(auditorId + "," + currentUser.getString("id"));
                        String nickname = currentUser.getString("username");
                        teachingBook.setAuditorName(auditorName + "、" + nickname);
                    }
                }
            }

        }
        auditRecord.setCreateTime(new Date());

        teachingBookAuditRecordService.insert(auditRecord);
        this.update(teachingBook);
        return teachingBook;
    }


    @Override
    public String publishTeachingBook(String id, Integer status) {
        TeachingBook teachingBook = this.getById(id);
        if (teachingBook == null) {
            return "该教案不存在";
        }

        teachingBook.setAuditStatus(status);
        this.update(teachingBook);

        return null;
    }


    @Override
    public JSONObject queryById(String id) {
        return null;
    }


    /**
     * 准备条件
     *
     * @param request
     * @param qw
     */
    private QueryWrapper prepareParams(QueryTeachingBookRequest request, QueryWrapper qw) {
        if (request.getIds() != null && request.getIds().length > 0) {
            qw.in("id", request.getIds());
        }
        if (!StringUtils.isEmpty(request.getSchoolId())) {
            qw.eq("school_id", request.getSchoolId());
        }
        if (!StringUtils.isEmpty(request.getTeacherId())) {
            qw.eq("teacher_id", request.getTeacherId());
        }
        if (!StringUtils.isEmpty(request.getRefId())) {
            qw.eq("ref_id", request.getRefId());
        }
        if (!StringUtils.isEmpty(request.getRefType())) {
            qw.eq("ref_type", request.getRefType());
        }
        return qw;
    }

    @Override
    public Integer queryTeachingBookCount(String teacherId, Integer refId, Integer contractId) {
        QueryWrapper<TeachingBook> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teacher_id", teacherId);
        if (contractId != null) {
            queryWrapper.eq("contract_id", contractId);
        }
        queryWrapper.eq("ref_id", refId);
        return getDao().selectCount(queryWrapper);
    }

    @Override
    public TeachingBook queryByPaikeId(String paikeId) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("lw_paike_id", paikeId);
        qw.orderByDesc("create_time");
        List<TeachingBook> list = this.dao.selectList(qw);
        if (!CollectionUtils.isEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public TeachingBookDto queryTeachingBookInfoByPaikeId(String lwPaikeId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("lw_paike_id", lwPaikeId);

        TeachingBookDto teachingBookDto = this.selectOne(queryWrapper, TeachingBookDto.class);

        if (teachingBookDto == null) {
            List<TeachingBookTemplate> teachingBookTemplates = teachingBookTemplateService.queryAll();

            teachingBookDto = new TeachingBookDto();
            if (StringUtils.isEmpty(teachingBookDto.getUniqueKey())) {
                teachingBookDto.setUniqueKey(UUID.randomUUID().toString());
            }
            teachingBookDto.setTeachingBookTemplates(teachingBookTemplates);
            return teachingBookDto;
        } else {
            QueryWrapper qw = new QueryWrapper();
            qw.eq("teaching_book_id", teachingBookDto.getId());
            TeachingBookPlanBind teachingBookPlanBind = teachingBookPlanBindMapper.selectOne(qw);
            if (teachingBookPlanBind != null) {
                teachingBookDto.setTeachingPlanDetailId(teachingBookPlanBind.getPlanDetailId());
            }
        }
        if (StringUtils.isEmpty(teachingBookDto.getUniqueKey())) {
            teachingBookDto.setUniqueKey(UUID.randomUUID().toString());
        }
        teachingBookDto.setModules(teachingBookModuleService.queryTeachingBookModuleListByParentId(teachingBookDto.getId()));

        return teachingBookDto;
    }

    @Override
    public Integer queryCountByRefId(String refId, Integer classType) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("ref_type", classType);
        queryWrapper.eq("ref_id", refId);
        queryWrapper.ne("audit_status", 0);
        return this.selectCount(queryWrapper);
    }



    @Override
    public NowTeachingBookStudentResultDto queryNowTeachingBookStudentResult(String teachingBookId, String studentId) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("teaching_book_id", teachingBookId);

        TeachingBook teachingBook = this.dao.selectById(teachingBookId);
        if (teachingBook == null) {
            return new NowTeachingBookStudentResultDto();
        }

        //查询是否作答
        TeachingBookStudentResult teachingBookStudentResult = teachingBookStudentResultService.queryByIdStudentAndTeachingBookId(studentId, teachingBookId);
        //作答状态：1已作答，0未作答
        Integer savedStatus = 0;
        if (teachingBookStudentResult != null) {
            savedStatus = teachingBookStudentResult.getStatus();
        }

        NowTeachingBookStudentResultDto dto = new NowTeachingBookStudentResultDto();
        dto.setTopic(teachingBook.getName());
        List<StudentErrorQuestionResultDto> errorQuestionResultDtos = new ArrayList<>();

        QueryTeachingBookModuleDetailRequest detailRequest = new QueryTeachingBookModuleDetailRequest();
        detailRequest.setTeachingBookId(teachingBookId);
        detailRequest.setModuleId(TeachingBookConstant.TeachingBookTemplate.ERRORQUESTION);
        List<TeachingBookModuleDetail> errorQuestions = teachingBookModuleDetailService.queryTeachingBookModuleDetailByParams(detailRequest);
        //查询学生备课错题数据
        if (!CollectionUtils.isEmpty(errorQuestions)) {
            for (TeachingBookModuleDetail errorQuestion : errorQuestions) {
                StudentErrorQuestionResultDto errorQuestionResultDto = new StudentErrorQuestionResultDto();

                String questionId ;
                if (errorQuestion.getContentType().equals(TeachingBookConstant.ModuleContentType.ERROQUESTION)) {
                    UserErrorQuestion userErrorQuestion = userErrorQuestionService.getById(errorQuestion.getResourceId());
                    if (userErrorQuestion == null) {
                        questionId = errorQuestion.getResourceId();
                    }else{
                        questionId = userErrorQuestion.getQuestionId();
                    }
                } else {
                    questionId = errorQuestion.getResourceId();
                }
                QuestionDto question = questionService.getQuestion(questionId, null);
                errorQuestionResultDto.setQuestionDto(question);

                //查询错题作答结果
                TeachingBookStudentQuestionResult questionResult = teachingBookStudentQuestionResultService.queryOneByParam(studentId, teachingBookId, errorQuestion.getResourceId(), 1);
                if (questionResult != null) {
                    errorQuestionResultDto.setCorrect(questionResult.getCorrect());
                }
                errorQuestionResultDtos.add(errorQuestionResultDto);
            }
        }
        List<TeachingBookQuestionStudentResultDto> questionStudentResultDtos = new ArrayList<>();
        //查询学生习题数据
        //2.变试题;3.普通试题;4.考点分析;5.文本/段落;6.思维导图;7.练习;8.自编试题;9.相似题
        qw.in("content_type", Arrays.asList(2, 3, 8, 9));
        List<TeachingBookModuleDetail> questions = teachingBookModuleDetailService.selectList(qw, TeachingBookModuleDetail.class);
        if (!CollectionUtils.isEmpty(questions)) {
            for (TeachingBookModuleDetail moduleDetail : questions) {
                TeachingBookQuestionStudentResultDto studentResultDto = new TeachingBookQuestionStudentResultDto();

                QuestionDto question = questionService.getQuestion(moduleDetail.getResourceId(), null);
                studentResultDto.setQuestionDto(question);

                //查询错题作答结果
                TeachingBookStudentQuestionResult questionResult = teachingBookStudentQuestionResultService.queryOneByParam(studentId, teachingBookId, moduleDetail.getResourceId(), 2);
                if (questionResult != null) {
                    studentResultDto.setCorrect(questionResult.getCorrect());
                }
                questionStudentResultDtos.add(studentResultDto);
            }
        }
        dto.setErrorQuestionResultDtos(errorQuestionResultDtos);
        dto.setErrorQuestionCount(errorQuestionResultDtos.size());
        dto.setQuestionCount(questionStudentResultDtos.size());
        dto.setQuestionStudentResultDtos(questionStudentResultDtos);
        dto.setSavedStatus(savedStatus);
        return dto;
    }

    @Override
    public Map<String, Object> chooseQuestionToCache(String uniqueKey, Integer type, String questionId) {
        if (StringUtils.isEmpty(uniqueKey) || StringUtils.isEmpty(questionId)) {
            return new HashMap<>();
        }
        QuestionDto question = questionService.getQuestion(questionId, null);
        if (question == null) {
            throw new XhException("试题不存在");
        }
        String key = uniqueKey + type;
        List<QuestionDto> questionDtos = (List<QuestionDto>) CacheUtils.get(key);
        if (CollectionUtils.isEmpty(questionDtos)) {
            questionDtos = new ArrayList<>();
            questionDtos.add(question);
        } else {
            long count = questionDtos.stream().filter(item -> item.getId().equals(questionId)).count();
            if (count >= 1) {
                throw new XhException("该试题已存在");
            }

            questionDtos.add(question);
        }
        CacheUtils.set(key, questionDtos);

        Map<String, Object> retMap = new HashMap<>();
        retMap.put("type", type);
        retMap.put("questionDtos", questionDtos);
        return retMap;
    }

    @Override
    public Map<String, Object> queryTeachingBookQuestionCacheByKey(String uniqueKey, Integer type) {
        if (StringUtils.isEmpty(uniqueKey)) {
            return new HashMap<>();
        }
        String key = uniqueKey + type;
        List<QuestionDto> questionDtos = (List<QuestionDto>) CacheUtils.get(key);

        HashMap<String, Object> retMap = new HashMap<>();
        retMap.put("type", type);
        retMap.put("questionDtos", questionDtos);

        return retMap;
    }

    @Override
    public void removeTeachingBookQuestionCache(String uniqueKey, Integer type) {
        CacheUtils.delete(uniqueKey + type);
    }

    @Override
    public List<TeachingBook> queryAcceptTeachingBookByTeacherId(String teacherId,String refId) {
        QueryWrapper<TeachingBook> qw = new QueryWrapper<>();
        qw.eq("teacher_id", teacherId);
        qw.eq("ref_id", refId);
        qw.eq("audit_status", TeachingBookConstant.TeachingBookAuditStatus.MASTER);
        qw.orderByDesc("school_time");

        return this.dao.selectList(qw);
    }

}
